import {errorHandler} from "./requestErrorHandle"
import store from "../store"

const baseURL = "http://1.12.227.37:1337/";

function request(options = {}) {
    if (store.getters["user/hasLogin"]) {
        if (!options.headers) options.headers = {};
        options.headers.Authorization = `Bearer ${store.getters["user/getAccessToken"]}`
    }
    return new Promise((resolve, reject) => {
        let data = {...options}
        data.url = baseURL + (options.url ?? '')
        data.method = options.method || 'GET'
        data.data = options.data || {}
        uniCloud.callFunction({
            name: 'request',
            data
        }).then((res) => {
            console.log("request", options, "success", res)
            if (res.result.res.statusCode !== 200 || res.result.data.errMsg) {
                errorHandler(res.result)
                reject(res)
            }

            if (res.result.data.msg) {
                uni.showToast({
                    icon: 'none',
                    title: res.result.data.msg,
                    duration: 3000
                });
            }
            resolve(res.result.data)
        }).catch((err) => {
            console.log("request", options, "fail", err)
            errorHandler(err.result)
            reject(err)
        })
    })
}

['get', 'post', 'put', 'delete', 'patch'].forEach((method) => {
    request[method] = (url, data, options) => {
        return request({
            ...options,
            url,
            data,
            method,
        })
    }
})

export default request
